import React, { Component } from 'react';
import store from './store';
import { getInputChangeAction, getAddItemAction, getDeleteItemAction,getInitList} from './store/actionCreator';
import TodoListUI from './TodoListUI';




class TodoList extends Component {

    constructor(props) {
        super(props);
        this.state = store.getState();
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleStoreChange = this.handleStoreChange.bind(this);
        this.handleButtonClick = this.handleButtonClick.bind(this);
        this.handleItemDelete = this.handleItemDelete.bind(this);
        store.subscribe(this.handleStoreChange);
    }

    render() {
        return (
            <TodoListUI
                inputValue={this.state.inputValue}
                list = {this.state.list}
                handleInputChange={this.handleInputChange}
                handleButtonClick={this.handleButtonClick}
                handleItemDelete={this.handleItemDelete}
            />
        )
    }

    componentDidMount() {
        // redux-thunk 中使用
        // const action = getTodoList();
        // store.dispatch(action);

        // axios.get('/list.json').then((res) => {
        //     const data = res.data;
        //     const action = InitListAction(data);
        //     store.dispatch(action);
        // })

        const action = getInitList();
        store.dispatch(action)
    }

    handleInputChange(e) {
        // 旧写法：
        // // 1.改变redux的内容：创建action（对应reducer中的action）
        // const action = {
        //     // 定义action对应的input类型
        //     type: CHANGE_INPUT_VALUE,
        //     // 传递数据
        //     value: e.target.value
        // }
        // 新写法：
        const action = getInputChangeAction(e.target.value);

        // 2.将数据传给store中
        store.dispatch(action)
    }

    handleStoreChange() {
        this.setState(store.getState())
    }

    handleButtonClick() {
        // const action = {
        //     type: ADD_TODO_ITEM 
        // }
        const action = getAddItemAction();
        store.dispatch(action);
    }

    handleItemDelete(index){
        // const action = {
        //     type: DELETE_TODO_ITEM,
        //     index
        // }
        const action = getDeleteItemAction(index);
        store.dispatch(action);
    }
}
export default TodoList